package org.example;

import org.example.tool.OptionalBean;
import org.example.tool.User;
import org.junit.Test;

import java.util.Objects;

/**
 * @Classname NPEtest
 * @Description TODO
 * @Date 2020/10/26 11:27 上午
 * @Created by xiangjd
 */
public class NPEtest {
    public static void main(String[] args) {

        User axin = new User();
        User.School school = new User.School();
        axin.setName("hello");

        if (Objects.nonNull(axin) && Objects.nonNull(axin.getSchool())) {
            User.School userSc = axin.getSchool();
            System.out.println(userSc.getAdress());
        }
    }

    @Test
    public void test1() {
        User axin = new User();
        User.School school = new User.School();
        axin.setName("hello");

        if (Objects.nonNull(axin) && Objects.nonNull(axin.getSchool())) {
            User.School userSc = axin.getSchool();
            System.out.println(userSc.getAdress());
        }
    }

    @Test
    public void test2() {
        User axin = new User();
        User.School school = new User.School();
        axin.setName("hello");

        // 1. 基本调用
        String value1 = OptionalBean.ofNullable(axin)
                .getBean(User::getSchool)
                .getBean(User.School::getAdress).get();
        System.out.println(value1);
    }

    @Test
    public void test3() {
        User axin = new User();
        User.School school = new User.School();
        axin.setName("hello");

        // 1. 基本调用
        String value1 = OptionalBean.ofNullable(axin)
                .getBean(User::getSchool)
                .getBean(User.School::getAdress).get();
        System.out.println(value1);

        // 2. 扩展的 isPresent方法 用法与 Optional 一样
        boolean present = OptionalBean.ofNullable(axin)
                .getBean(User::getSchool)
                .getBean(User.School::getAdress).isPresent();
        System.out.println(present);


        // 3. 扩展的 ifPresent 方法
        OptionalBean.ofNullable(axin)
                .getBean(User::getSchool)
                .getBean(User.School::getAdress)
                .ifPresent(adress -> System.out.println(String.format("地址存在:%s", adress)));

        // 4. 扩展的 orElse
        String value2 = OptionalBean.ofNullable(axin)
                .getBean(User::getSchool)
                .getBean(User.School::getAdress).orElse("家里蹲");

        System.out.println(value2);

        // 5. 扩展的 orElseThrow
        try {
            String value3 = OptionalBean.ofNullable(axin)
                    .getBean(User::getSchool)
                    .getBean(User.School::getAdress).orElseThrow(() -> new RuntimeException("空指针了"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
